package com.tf_cut.backend.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.tf_cut.backend.common.pojo.PageInfo;
import com.tf_cut.backend.common.service.CommonServiceImpl;
import com.tf_cut.backend.mapper.SetHistoryMapper;
import com.tf_cut.backend.platform.pojo.SetHistory;
import com.tf_cut.backend.platform.repository.SetHistoryRepository;
import com.tf_cut.backend.platform.service.SetHistoryService;
import com.tf_cut.backend.platform.vo.SetHistoryVo;
import com.tf_cut.backend.seller.vo.SellerOrderVo;

@Service
@Transactional
@Slf4j
public class SetHistoryServiceImpl extends CommonServiceImpl<SetHistoryVo, SetHistory, String> implements SetHistoryService{
	
	@Autowired
	private SetHistoryRepository SetHistoryRepository;
	
	@Autowired
	private SetHistoryMapper setHistoryMapper;
	
	

	@Override
	public String importData(MultipartFile file) {
	        InputStream fis = null;
	        Workbook workBook = null;
	        try {
				fis = file.getInputStream();
				// 获取文件名
	            String fileName = file.getOriginalFilename();
	            // 截取文件后缀名
	            String hz = fileName.substring(fileName.lastIndexOf("."), fileName.length());
	            if (".xlsx".equalsIgnoreCase(hz)) {
	                workBook = new XSSFWorkbook(fis);
	            } else {
	                workBook = new HSSFWorkbook(fis);
	            }
	         // 遍历sheet，获取sheet中数据
	            Sheet tcsSheet;
	            // 行
	            Row row;
	            int rows = workBook.getSheetAt(0).getPhysicalNumberOfRows();
	            int total = rows - 1;
	            if (total < 1) {
	                return "空数据不能导入";
	            }
	            // 判断文件后缀是“.xlsx”还是“.xls”，并进行不同的操作
	            if (".xlsx".equalsIgnoreCase(hz)) {
	                tcsSheet = (XSSFSheet) workBook.getSheetAt(0);
	            } else {
	                tcsSheet = (HSSFSheet) workBook.getSheetAt(0);
	            }
	            DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
	            for (int r = 0; r < 1; r++) {
	            	// 获取每一行
                    if (".xlsx".equalsIgnoreCase(hz)) {
                        row = (XSSFRow) tcsSheet.getRow(r);
                    } else {
                        row = (HSSFRow) tcsSheet.getRow(r);
                    }
                 // 行为空
                    if (row == null) {
                        continue;
                    }
	            	// 纳税人名称
                    String payTaxName = getCellValueToString(row.getCell(0));
                    if(!payTaxName.equals("纳税人名称")){
                    	return "导入模板不正确,请重新下载导入模板";
                    }
                 // 税号
                    String taxNumber = getCellValueToString(row.getCell(1));
                    if(!taxNumber.equals("税号")){
                    	return "导入模板不正确,请重新下载导入模板";
                    }
                 // 税种
                    String taxType = getCellValueToString(row.getCell(2));
                    if(!taxType.equals("税种")){
                    	return "导入模板不正确,请重新下载导入模板";
                    }
                 // 销售收入
                    String salesInto = getCellValueToString(row.getCell(3));
                    if(!salesInto.equals("销售收入")){
                    	return "导入模板不正确,请重新下载导入模板";
                    }
                 // 税额
                    String taxMoney = getCellValueToString(row.getCell(4));
                    if(!taxMoney.equals("税额")){
                    	return "导入模板不正确,请重新下载导入模板";
                    }
                 // 税款所属开始时间
                    String starstarTime = getCellValueToString(row.getCell(5));
                    if(!starstarTime.equals("税款所属开始时间")){
                    	return "导入模板不正确,请重新下载导入模板";
                    }
                    // 税款所属结束时间
                    String starendTime = getCellValueToString(row.getCell(6));
                    if(!starendTime.equals("税款所属结束时间")){
                    	return "导入模板不正确,请重新下载导入模板";
                    }
	            }
	         // 从sheet的第2行，及r=1开始读
                for (int r = 1; r < tcsSheet.getPhysicalNumberOfRows(); r++) {
                	 // 获取每一行
                    if (".xlsx".equalsIgnoreCase(hz)) {
                        row = (XSSFRow) tcsSheet.getRow(r);
                    } else {
                        row = (HSSFRow) tcsSheet.getRow(r);
                    }
                 // 行为空
                    if (row == null) {
                        continue;
                    }
                 // 纳税人名称
                    String payTaxName = getCellValueToString(row.getCell(0));
                 // 税号
                    String taxNumber = getCellValueToString(row.getCell(1));
                 // 税种
                    String taxType = getCellValueToString(row.getCell(2));
                 // 销售收入
                    String salesInto = getCellValueToString(row.getCell(3));
                 // 税额
                    String taxMoney = getCellValueToString(row.getCell(4));
                 // 税款所属开始时间
                    String starstarTime = getCellValueToString(row.getCell(5));
                 // 税款所属结束时间
                    String starendTime = getCellValueToString(row.getCell(6));
                    SetHistory setHistory = new SetHistory();
                    setHistory.setPayTaxName(payTaxName);
                    setHistory.setTaxNumber(taxNumber);
                    setHistory.setTaxType(taxType);
                    setHistory.setSalesInto(Double.parseDouble(salesInto));
                    setHistory.setTaxMoney(Double.parseDouble(taxMoney));
                    setHistory.setStarstarTime(HSSFDateUtil.getJavaDate(Double.parseDouble(starstarTime)));
                    setHistory.setStarendTime(HSSFDateUtil.getJavaDate(Double.parseDouble(starendTime)));
					setHistory.setCreateTime(new Date());
                    SetHistoryRepository.save(setHistory);
                    
                }
                
	            
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return "导入成功";
	}
	
	
	   /**
     * 获取列值
     *
     * @param cell
     * @return
     */
    private String getCellValueToString(Cell cell) {
        String value = StringUtils.EMPTY;
        if (null == cell)
            return value;
        cell.setCellType(CellType.STRING);
        value = cell.getStringCellValue();
        return value;
    }


	@Override
	public PageInfo<SetHistoryVo> queryByHistory(int page, int rows, String paytaxName, String starSalesInto, String endSalesInto,
			String startaxMoney, String endtaxMoney, String starStarTime, String endStarTime, String starEndTime,
			String endEndTime,String taxNumber) {
		com.github.pagehelper.PageHelper.startPage(page,rows);
		if(starStarTime != null && !starStarTime.equals("")){
			starStarTime += starStarTime+"00:00:00";
		}
		if(endStarTime != null && !endStarTime.equals("")){
			endStarTime += endStarTime+"23:59:59";
		}
		if(starEndTime != null && !starEndTime.equals("")){
			starEndTime += starEndTime+"00:00:00";
		}
		if(endEndTime != null && !endEndTime.equals("")){
			endEndTime += endEndTime+"23:59:59";
		}
        List<SetHistoryVo> list = setHistoryMapper.queryByHistory(paytaxName,starSalesInto,endSalesInto,startaxMoney,endtaxMoney,starStarTime,endStarTime,starEndTime ,endEndTime,taxNumber);
        com.github.pagehelper.PageInfo<SetHistoryVo> pageInfo = new com.github.pagehelper.PageInfo<>(list);
		  PageInfo<SetHistoryVo> returnPageInfo = new PageInfo<>();
	        returnPageInfo.setPage(pageInfo.getPageNum());
	        returnPageInfo.setPageSize(pageInfo.getPageSize());
	        returnPageInfo.setRows(pageInfo.getList());
	        returnPageInfo.setRecords((int) pageInfo.getTotal());
	        returnPageInfo.setTotal(pageInfo.getPages());
	        return returnPageInfo;
	}
	

}
